import request from '@/utils/request'
import router from '@/router'
import Cookies from 'js-cookie'
import { getTabAuth } from '@/api/message'

export default {
    /**
     * 获取登陆用户信息
     */
    async fetchUserInfo({ commit }) {
        console.log('store dispatch:', 11111111, commit)
        // Cookies.set('manager_session_id', '2032282cf4a946aaad3f519a68acfed7')
        const res = await request({
            url: '/yunLspUser/getUser'
        })
        if (res.data) {
            commit('SET_USER', res.data)
        }

        return res.data
    },
    setGlobalClick({ state }, data) {
        state.globalClick[data.key] = data.value
    },
    async setRoutes({ state }) {
        if (state.hasInitRoutes) return
        if (process.env.NODE_ENV === 'development') {
            state.routes = router.options.routes
            state.hasInitRoutes = true
            router.replace('/company-manage')
            return
        }
        const res = await getTabAuth(Cookies.get('manager_session_id'))
        res.data = res.data.filter(i => i.href)
        const arr = []
        router.options.routes.filter(i => !i.hidden).forEach(i => {
            if (res.data.findIndex(j => i.path === j.href) > -1) {
                arr.push(i)
            }
        })
        const expressIndex = arr.findIndex(i => i.name === 'Express')
        if (expressIndex > -1) {
            arr[expressIndex].children.forEach(i => {
                if (res.data.find(j => j.href === '/express').children.findIndex(k => k.href === i.path) === -1) {
                    i.noAuth = true
                }
            })
            arr[expressIndex].children = arr[expressIndex].children.filter(i => !i.noAuth)
        }
        state.routes = arr
        if (res.data.findIndex(i => i.href === '/company-manage') > -1) {
            router.replace('/company-manage')
        } else if (res.data.length > 0) {
            router.replace(res.data[0].href)
        }
        state.hasInitRoutes = true
    }
}